package situ.com.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class BindServiceActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "BindServiceActivity";
    
    private Button mBtnBindService;
    private Button mBtnCallServiceMehtod;
    private Button mBtnStopService;

    private  MyConnection mConnetion;
    private BindService.MyBinder mBinder;

    // ServiceConnection:用来绑定客户端和服务器，就是用来绑定Service
    private class MyConnection implements ServiceConnection{

        // 当客户端绑定Service时候调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected() called with: " + "name = [" + name + "], service = [" + service + "]");
            mBinder = (BindService.MyBinder) service;
        }

        // 当客户端和服务器断开的时候调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected() called with: " + "name = [" + name + "]");
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_service);
        mBtnBindService = (Button) findViewById(R.id.btn_bind_service);
        mBtnCallServiceMehtod = (Button) findViewById(R.id.btn_call_service_method);
        mBtnStopService = (Button) findViewById(R.id.btn_stop_service);
        mBtnBindService.setOnClickListener(this);
        mBtnCallServiceMehtod.setOnClickListener(this);
        mBtnStopService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, BindService.class);
        switch (v.getId()) {
            case R.id.btn_bind_service:
                if (mConnetion == null) {
                    mConnetion = new MyConnection();
                }
                // 绑定服务 onCreate->onBind
                bindService(intent, mConnetion, BIND_AUTO_CREATE);
                break;
            case R.id.btn_call_service_method:
                if (mBinder != null) {
                    mBinder.play();
                    mBinder.stop();
                }
                break;
            case R.id.btn_stop_service:
                // 解除绑定
                unbindService(mConnetion);
                mConnetion = null;
                mBinder = null;
                break;
        }
    }
}
